<template>
  <div class="report-center-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>报表中心</span>
        </div>
      </template>

      <!-- 统计卡片行 -->
      <div class="stats-row">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-label">租户总数</div>
            <div class="stat-value">{{ tenantCount }}</div>
            <div class="stat-icon"><el-icon><User /></el-icon></div>
          </div>
        </el-card>

        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-label">问题反馈</div>
            <div class="stat-value">{{ feedbackCount }}</div>
            <div class="stat-icon"><el-icon><Message /></el-icon></div>
          </div>
        </el-card>

        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-label">今日解决</div>
            <div class="stat-value">{{ todaySolvedCount }}</div>
            <div class="stat-icon"><el-icon><Check /></el-icon></div>
          </div>
        </el-card>

        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-label">剩余问题</div>
            <div class="stat-value">{{ remainingIssuesCount }}</div>
            <div class="stat-icon"><el-icon><Warning /></el-icon></div>
          </div>
        </el-card>
      </div>

      <div class="chart-row">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>出租率统计</span>
              <el-select v-model="rentalRateTimeRange" placeholder="选择时间范围" size="small" @change="handleRentalRateTimeRangeChange">
                <el-option label="日统计" value="day" />
                <el-option label="月统计" value="month" />
                <el-option label="季度统计" value="quarter" />
              </el-select>
            </div>
          </template>
          <div ref="rentalRateChartRef" class="chart"></div>
        </el-card>

        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>合同到期预警</span>
            </div>
          </template>
          <div ref="contractWarningChartRef" class="chart"></div>
        </el-card>
      </div>

      <div class="chart-row">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>财务汇总报表</span>
            </div>
          </template>
          <div ref="financialSummaryChartRef" class="chart"></div>
        </el-card>

        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>租客画像分析</span>
            </div>
          </template>
          <div ref="tenantProfileChartRef" class="chart"></div>
        </el-card>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import { User, Message, Check, Warning } from '@element-plus/icons-vue'
import reportService from '../../services/reportService.ts'

// 统计数据
const tenantCount = ref(0)
const feedbackCount = ref(0)
const todaySolvedCount = ref(0)
const remainingIssuesCount = ref(0)

// 时间范围选择
const rentalRateTimeRange = ref('month')

// 图表引用
const rentalRateChartRef = ref<HTMLDivElement | null>(null)
const contractWarningChartRef = ref<HTMLDivElement | null>(null)
const financialSummaryChartRef = ref<HTMLDivElement | null>(null)
const tenantProfileChartRef = ref<HTMLDivElement | null>(null)

// 图表实例
let rentalRateChartInstance: echarts.ECharts | null = null
let contractWarningChartInstance: echarts.ECharts | null = null
let financialSummaryChartInstance: echarts.ECharts | null = null
let tenantProfileChartInstance: echarts.ECharts | null = null

// 生命周期钩子
onMounted(() => {
  // 获取统计数据
  fetchStatisticsData()
  nextTick(() => {
    initRentalRateChart()
    initContractWarningChart()
    initFinancialSummaryChart()
    initTenantProfileChart()
  })
})

// 获取统计数据
const fetchStatisticsData = () => {
  // 获取租户统计
  reportService.getReportStatistics('tenant').then((res: any) => {
    if (res.code === 200) {
      tenantCount.value = res.data.tenantCount
    }
  }).catch((error: any) => {
    console.error('获取租户统计数据失败:', error)
  })

  // 获取反馈统计
  reportService.getReportStatistics('feedback').then((res: any) => {
    if (res.code === 200) {
      feedbackCount.value = res.data.feedbackCount
      todaySolvedCount.value = res.data.todaySolvedCount
      remainingIssuesCount.value = res.data.remainingIssuesCount
    }
  }).catch((error: any) => {
    console.error('获取反馈统计数据失败:', error)
  })
}

// 初始化出租率统计图表
const initRentalRateChart = () => {
  if (rentalRateChartRef.value && !rentalRateChartInstance) {
    rentalRateChartInstance = echarts.init(rentalRateChartRef.value)
    updateRentalRateChart()
  }
}

// 更新出租率统计图表
const updateRentalRateChart = () => {
  if (!rentalRateChartInstance) return

  // 从API获取出租率数据
  reportService.getReportStatistics('rentalRate', [], rentalRateTimeRange.value).then((res: any) => {
    if (res.code === 200) {
      const xAxisData = res.data.xAxisData
      const seriesData = res.data.seriesData

      const option = {
        tooltip: {
          trigger: 'axis'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: xAxisData
        },
        yAxis: {
          type: 'value',
          max: 100,
          axisLabel: {
            formatter: '{value}%'
          }
        },
        series: [
          {
            name: '出租率',
            type: 'line',
            stack: '总量',
            data: seriesData,
            smooth: true,
            lineStyle: {
              width: 3
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(128, 189, 255, 0.6)' },
                { offset: 1, color: 'rgba(128, 189, 255, 0.1)' }
              ])
            },
            markLine: {
              data: [
                {
                  name: '警戒线',
                  yAxis: 70,
                  lineStyle: {
                    color: 'rgb(255, 99, 132)'
                  },
                  label: {
                    formatter: '警戒线 70%'
                  }
                }
              ]
            }
          }
        ]
      }

      rentalRateChartInstance.setOption(option)
    }
  }).catch((error: any) => {
    console.error('获取出租率数据失败:', error)
    // 使用默认数据
    let xAxisData: string[] = []
    let seriesData: number[] = []

    if (rentalRateTimeRange.value === 'day') {
      // 日统计
      xAxisData = Array.from({ length: 30 }, (_, i) => `${i + 1}日`)
      seriesData = Array.from({ length: 30 }, () => 70 + Math.floor(Math.random() * 30))
    } else if (rentalRateTimeRange.value === 'month') {
      // 月统计
      xAxisData = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
      seriesData = [85, 82, 78, 80, 85, 90, 95, 98, 92, 88, 85, 87]
    } else if (rentalRateTimeRange.value === 'quarter') {
      // 季度统计
      xAxisData = ['Q1', 'Q2', 'Q3', 'Q4']
      seriesData = [82, 88, 94, 87]
    }" + "

      const option = {
        tooltip: {
          trigger: 'axis'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: xAxisData
        },
        yAxis: {
          type: 'value',
          max: 100,
          axisLabel: {
            formatter: '{value}%'
          }
        },
        series: [
          {
            name: '出租率',
            type: 'line',
            stack: '总量',
            data: seriesData,
            smooth: true,
            lineStyle: {
              width: 3
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(128, 189, 255, 0.6)' },
                { offset: 1, color: 'rgba(128, 189, 255, 0.1)' }
              ])
            },
            markLine: {
              data: [
                {
                  name: '警戒线',
                  yAxis: 70,
                  lineStyle: {
                    color: 'rgb(255, 99, 132)'
                  },
                  label: {
                    formatter: '警戒线 70%'
                  }
                }
              ]
            }
          }
        ]
      }

      rentalRateChartInstance.setOption(option)
  })

  const option = {
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xAxisData
    },
    yAxis: {
      type: 'value',
      max: 100,
      axisLabel: {
        formatter: '{value}%'
      }
    },
    series: [
      {
        name: '出租率',
        type: 'line',
        stack: '总量',
        data: seriesData,
        smooth: true,
        lineStyle: {
          width: 3
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(128, 189, 255, 0.6)' },
            { offset: 1, color: 'rgba(128, 189, 255, 0.1)' }
          ])
        },
        markLine: {
          data: [
            {
              name: '警戒线',
              yAxis: 70,
              lineStyle: {
                color: 'rgb(255, 99, 132)'
              },
              label: {
                formatter: '警戒线 70%'
              }
            }
          ]
        }
      }
    ]
  }

  rentalRateChartInstance.setOption(option)
}

// 初始化合同到期预警图表
const initContractWarningChart = () => {
  if (contractWarningChartRef.value && !contractWarningChartInstance) {
    contractWarningChartInstance = echarts.init(contractWarningChartRef.value)

    // 从API获取合同到期数据
    reportService.getReportStatistics('contractWarning').then((res: any) => {
      if (res.code === 200) {
        const xAxisData = res.data.xAxisData
        const seriesData = res.data.seriesData

        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: xAxisData
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: '到期合同数',
              type: 'bar',
              data: seriesData,
              itemStyle: {
                color: function(params) {
                  const colorList = ['#ff4560', '#ff758f', '#ffb6c1', '#87cefa', '#4682b4', '#5f9ea0']
                  return colorList[params.dataIndex]
                }
              },
              label: {
                show: true,
                position: 'top'
              }
            }
          ]
        }

        contractWarningChartInstance.setOption(option)
      }
    }).catch((error: any) => {
      console.error('获取合同到期数据失败:', error)
      // 使用默认数据
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: ['1个月内', '2个月内', '3个月内', '4个月内', '5个月内', '6个月内']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '到期合同数',
            type: 'bar',
            data: [12, 19, 8, 5, 3, 2],
            itemStyle: {
              color: function(params) {
                const colorList = ['#ff4560', '#ff758f', '#ffb6c1', '#87cefa', '#4682b4', '#5f9ea0']
                return colorList[params.dataIndex]
              }
            },
            label: {
              show: true,
              position: 'top'
            }
          }
        ]
      }

      contractWarningChartInstance.setOption(option)
    })
  }
}

// 初始化财务汇总报表图表
const initFinancialSummaryChart = () => {
  if (financialSummaryChartRef.value && !financialSummaryChartInstance) {
    financialSummaryChartInstance = echarts.init(financialSummaryChartRef.value)

    // 从API获取财务汇总数据
    reportService.getReportStatistics('financialSummary').then((res: any) => {
      if (res.code === 200) {
        const option = {
          tooltip: {
            trigger: 'item'
          },
          legend: {
            top: '5%',
            left: 'center'
          },
          series: [
            {
              name: '收入构成',
              type: 'pie',
              radius: ['40%', '70%'],
              avoidLabelOverlap: false,
              itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: false,
                position: 'center'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: 20,
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: false
              },
              data: res.data
            }
          ]
        }

        financialSummaryChartInstance.setOption(option)
      }
    }).catch((error: any) => {
      console.error('获取财务汇总数据失败:', error)
      // 使用默认数据
      const option = {
        tooltip: {
          trigger: 'item'
        },
        legend: {
          top: '5%',
          left: 'center'
        },
        series: [
          {
            name: '收入构成',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 20,
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: [
              { value: 65, name: '租金' },
              { value: 15, name: '水电费' },
              { value: 10, name: '物业费' },
              { value: 10, name: '其他费用' }
            ]
          }
        ]
      }

      financialSummaryChartInstance.setOption(option)
    })
  }
}

// 初始化租客画像分析图表
const initTenantProfileChart = () => {
  if (tenantProfileChartRef.value && !tenantProfileChartInstance) {
    tenantProfileChartInstance = echarts.init(tenantProfileChartRef.value)

    // 从API获取租客画像数据
    reportService.getReportStatistics('tenantProfile').then((res: any) => {
      if (res.code === 200) {
        const xAxisData = res.data.xAxisData
        const seriesData = res.data.seriesData

        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'value'
          },
          yAxis: {
            type: 'category',
            data: xAxisData
          },
          series: [
            {
              name: '租客数量',
              type: 'bar',
              data: seriesData,
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                  { offset: 0, color: 'rgba(0, 191, 255, 0.8)' },
                  { offset: 1, color: 'rgba(0, 191, 255, 0.2)' }
                ])
              },
              label: {
                show: true,
                position: 'right'
              }
            }
          ]
        }

        tenantProfileChartInstance.setOption(option)
      }
    }).catch((error: any) => {
      console.error('获取租客画像数据失败:', error)
      // 使用默认数据
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value'
        },
        yAxis: {
          type: 'category',
          data: ['20-30岁', '30-40岁', '40-50岁', '50-60岁', '60岁以上']
        },
        series: [
          {
            name: '租客数量',
            type: 'bar',
            data: [45, 30, 15, 8, 2],
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                { offset: 0, color: 'rgba(0, 191, 255, 0.8)' },
                { offset: 1, color: 'rgba(0, 191, 255, 0.2)' }
              ])
            },
            label: {
              show: true,
              position: 'right'
            }
          }
        ]
      }

      tenantProfileChartInstance.setOption(option)
    })
  }
}

// 处理时间范围变化
const handleRentalRateTimeRangeChange = () => {
  updateRentalRateChart()
}
</script>

<style scoped>
.report-center-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stats-row {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
}

.stat-card {
  flex: 1;
  padding: 16px;
}

.stat-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #1890ff;
  margin-bottom: 8px;
}

.stat-icon {
  align-self: flex-end;
  font-size: 24px;
  color: #1890ff;
}

.chart-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.chart-card {
  flex: 1;
}

.chart {
  height: 300px;
}

.chart {
  width: 100%;
  height: 300px;
}
</style>